package com.briup.jd2511.jd2511_product_source.service.impl;

import com.briup.jd2511.jd2511_product_source.dao.QuarantineRegistrationMapper;
import com.briup.jd2511.jd2511_product_source.exception.ServiceException;
import com.briup.jd2511.jd2511_product_source.pojo.QuarantineRegistration;
import com.briup.jd2511.jd2511_product_source.result.ResultCode;
import com.briup.jd2511.jd2511_product_source.service.QuarantineRegistrationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class QuarantineRegistrationServiceImpl implements QuarantineRegistrationService {

    @Autowired
    private QuarantineRegistrationMapper qrMapper;

    /**
     * 分页+条件查询检疫记录
     *
     * @param pageName
     * @param pageSize
     * @param grMechanism 检疫机构
     * @param bQualified  检疫结果
     * @return
     */
    @Override
    public PageInfo<QuarantineRegistration> findByPage(Integer pageName, Integer pageSize, String grMechanism, String bQualified) {
        PageHelper.startPage(pageName,pageSize);
        List<QuarantineRegistration> list= qrMapper.queryAllQuarantineRegistration(grMechanism,bQualified);
        PageInfo<QuarantineRegistration> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 添加/修改检疫登记信息
     *
     * @param qr
     */
    @Override
    public void saveOrUpdate(QuarantineRegistration qr) throws ServiceException {
        //含检疫记录ID,则为修改操作；不包含ID，则为新增操作。无论添加修改，检疫机构、图片地址不能为空，同时需同步修改批次表中该批次的检疫状态
        if(!StringUtils.hasText(qr.getGrMechanism())||!StringUtils.hasText(qr.getGrImg())){ //检疫机构、图片地址是否为空,只要一个为空，则返回错误信息
            throw new ServiceException(ResultCode.PARAM_IS_EMPTY); //参数不能为空
        }else if(qr.getGrId()==null){ //ID为空，则为新增
            //批次校验【保证该批次存在】
            if(qrMapper.selectBatchById(qr.getGrBatchId())==null){
                throw new ServiceException(ResultCode.DATA_IS_EMPTY);//数据不存在
            }
            //新增
            qrMapper.insert(qr);
        }else {
            //修改
            qrMapper.updateSelective(qr);
        }
        qrMapper.updateBatchQualified(qr.getGrBatchId(),qr.getBQualified());//修改指定批次检疫状态为"已检疫"及检疫合格状态 bQualified
    }
}
